package com.mlm.mlmapp.adapter.view.adapter;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.BannerFragment;
import com.mlm.mlmapp.adapter.view.PagerContainer;
import com.mlm.mlmapp.adapter.view.listener.OnBannerClickedListener;
import com.mlm.mlmapp.adapter.view.listener.OnGridItemSelectedListener;
import com.mlm.mlmapp.adapter.view.listener.OnSyClickedListener;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.utils.CommonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
		implements HTTPCons {
	private AQuery aq;
	private static final int TYPER_PAGER = 0;
	private static final int TYPE_ITEM = 1;
	private OnBannerClickedListener bannerListener;
	private static final int HEADER_PAGER_LAYOUT = 1;
	private FragmentActivity fa;
	private Context mContext;
	private List<JSONObject> array;
	private float centerX;
	Bitmap defualtBm;
	private OnGridItemSelectedListener mOnGridItemSelectedListener;
	private OnSyClickedListener onSyListener;
	public MainAdapter(Context context, List<JSONObject> array, FragmentActivity fa,
			OnBannerClickedListener bannerListener,
			OnSyClickedListener onSyListener) {
		this.array = array;
		this.mContext = context;
		this.fa = fa;
		this.bannerListener = bannerListener;
		this.onSyListener = onSyListener;
		defualtBm = BitmapFactory.decodeResource(context.getResources(),R.drawable.homelist_default);
		mOnGridItemSelectedListener = (OnGridItemSelectedListener) mContext;
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
			int viewType) {
		if (aq != null) {
			aq.recycle(parent);
		}
		aq = new AQuery(parent);
		if (viewType == TYPER_PAGER) {

			View v = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.include_view_pager, parent, false);
			final HeaderViewHolder headerHolder = new HeaderViewHolder(v);
			aq.ajax(get_sylists_action, JSONArray.class,
					new AjaxCallback<JSONArray>() {

						@SuppressLint("NewApi")
						@Override
						public void callback(String url, JSONArray array,
											 AjaxStatus status) {
							// TODO Auto-generated method stub
							if (status.getCode() == -101) {
								Toast.makeText(aq.getContext(), "网络异常,请检查网络",
										Toast.LENGTH_SHORT);
								return;
							}
							if (status.getCode() != 200) {
								Toast.makeText(aq.getContext(),
										"网络异常:" + status.getCode(),
										Toast.LENGTH_SHORT).show();
							} else {
								PagerAdapter adapter = new MyPagerAdapter(
										mContext, array, onSyListener);
								headerHolder.sylistViewPager
										.setAdapter(adapter);
								headerHolder.pc.setClipChildren(false);
								headerHolder.sylistViewPager
										.setOffscreenPageLimit(array.length());
								// A little space between pages
								// headerHolder.sylistViewPager
								// .setPageMargin(mContext
								// .getResources()
								// .getDimensionPixelSize(
								// R.dimen.viewpager_margin));
								headerHolder.sylistViewPager
										.setPageMargin((int) mContext
												.getResources()
												.getDimension(
														R.dimen.viewpager_margin));
								centerX = headerHolder.sylistViewPager.getX();
								headerHolder.sylistViewPager
										.setX(mContext
												.getResources()
												.getDimension(
														R.dimen.viewpager_first_margin_left));

								// headerHolder.sylistViewPager.setCurrentItem(0);//
								// 设置当前显示标签页为第一页
								headerHolder.sylistViewPager
										.setOnPageChangeListener(new SyListOnPageChangedListener(
												headerHolder.sylistViewPager));
							}
						}

					});
			aq.ajax(get_banner_action, JSONArray.class,
					new AjaxCallback<JSONArray>() {

						@Override
						public void callback(String url, JSONArray array,
											 AjaxStatus status) {
							// TODO Auto-generated method stub
							if (status.getCode() == -101) {
								Toast.makeText(aq.getContext(), "网络异常,请检查网络",
										Toast.LENGTH_SHORT);
								return;
							}
							if (status.getCode() != 200) {
								Toast.makeText(aq.getContext(),
										"网络异常:" + status.getCode(),
										Toast.LENGTH_SHORT).show();
							} else {
								List<BannerFragment> contents = new ArrayList<BannerFragment>();
								for (int i = 0; i < array.length(); i++) {
									// 新建Fragment的实例对象，并设置参数传递到Fragment中
									Bundle args = new Bundle();
									BannerFragment content = new BannerFragment(
											mContext, bannerListener);
									try {
										args.putString(JSON, array
												.getJSONObject(i).toString());
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									content.setArguments(args);
									contents.add(content);

									// 这个getSupportFragmentManager只有activity继承FragmentActivity才会有
								}
								BannerFragmentAdapter adapter = new BannerFragmentAdapter(
										fa.getSupportFragmentManager(),
										contents);
								headerHolder.bannerViewPager
										.setAdapter(adapter);
								headerHolder.bannerViewPager.setCurrentItem(0);// 设置当前显示标签页为第一页
								headerHolder.bannerViewPager
										.setOffscreenPageLimit(array.length());
								ViewGroup.LayoutParams lp = headerHolder.cursor
										.getLayoutParams();

								lp.width = headerHolder.cursorBackground.getWidth()
										/ array.length();

								headerHolder.cursor.setLayoutParams(lp);
								headerHolder.bannerViewPager
										.setOnPageChangeListener(new BannerOnPageChangedListener(
												headerHolder.bannerViewPager,
												headerHolder.cursorBackground
														.getWidth()
														/ array.length(),
												headerHolder.cursor));
								if (array.length() <= 1) {
									headerHolder.cursor
											.setVisibility(View.INVISIBLE);
									headerHolder.cursorBackground
											.setVisibility(View.INVISIBLE);
								}

							}
						}

					});
			// ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(mContext,
			// 0);
			// headerHolder.viewPager.setAdapter(pagerAdapter);
			// headerHolder.mIndicator.setViewPager(headerHolder.viewPager);

			return headerHolder;
		} else if (viewType == TYPE_ITEM) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.list_home, null);
			return new RecyclerViewHolder(view);
		}

		return null;
	}
	public void notifyDatasetChanged(){

	}
	@Override
	public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
		if (holder instanceof HeaderViewHolder) {
			final HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
//			aq.ajax(get_sylists_action, JSONArray.class,
//					new AjaxCallback<JSONArray>() {
//
//						@SuppressLint("NewApi")
//						@Override
//						public void callback(String url, JSONArray array,
//								AjaxStatus status) {
//							// TODO Auto-generated method stub
//							if (status.getCode() == -101) {
//								Toast.makeText(aq.getContext(), "网络异常,请检查网络",
//										Toast.LENGTH_SHORT);
//								return;
//							}
//							if (status.getCode() != 200) {
//								Toast.makeText(aq.getContext(),
//										"网络异常:" + status.getCode(),
//										Toast.LENGTH_SHORT).show();
//							} else {
//								PagerAdapter adapter = new MyPagerAdapter(
//										mContext, array, onSyListener);
//								headerHolder.sylistViewPager
//										.setAdapter(adapter);
//								headerHolder.pc.setClipChildren(false);
//								headerHolder.sylistViewPager
//										.setOffscreenPageLimit(array.length());
//								// A little space between pages
//								// headerHolder.sylistViewPager
//								// .setPageMargin(mContext
//								// .getResources()
//								// .getDimensionPixelSize(
//								// R.dimen.viewpager_margin));
//								headerHolder.sylistViewPager
//										.setPageMargin((int) mContext
//												.getResources()
//												.getDimension(
//														R.dimen.viewpager_margin));
//								centerX = headerHolder.sylistViewPager.getX();
//								headerHolder.sylistViewPager
//										.setX(mContext
//												.getResources()
//												.getDimension(
//														R.dimen.viewpager_first_margin_left));
//
//								// headerHolder.sylistViewPager.setCurrentItem(0);//
//								// 设置当前显示标签页为第一页
//								headerHolder.sylistViewPager
//										.setOnPageChangeListener(new SyListOnPageChangedListener(
//												headerHolder.sylistViewPager));
//							}
//						}
//
//					});
//			aq.ajax(get_banner_action, JSONArray.class,
//					new AjaxCallback<JSONArray>() {
//
//						@Override
//						public void callback(String url, JSONArray array,
//								AjaxStatus status) {
//							// TODO Auto-generated method stub
//							if (status.getCode() == -101) {
//								Toast.makeText(aq.getContext(), "网络异常,请检查网络",
//										Toast.LENGTH_SHORT);
//								return;
//							}
//							if (status.getCode() != 200) {
//								Toast.makeText(aq.getContext(),
//										"网络异常:" + status.getCode(),
//										Toast.LENGTH_SHORT).show();
//							} else {
//								List<BannerFragment> contents = new ArrayList<BannerFragment>();
//								for (int i = 0; i < array.length(); i++) {
//									// 新建Fragment的实例对象，并设置参数传递到Fragment中
//									Bundle args = new Bundle();
//									BannerFragment content = new BannerFragment(
//											mContext, bannerListener);
//									try {
//										args.putString(JSON, array
//												.getJSONObject(i).toString());
//									} catch (JSONException e) {
//										// TODO Auto-generated catch block
//										e.printStackTrace();
//									}
//									content.setArguments(args);
//									contents.add(content);
//
//									// 这个getSupportFragmentManager只有activity继承FragmentActivity才会有
//								}
//								BannerFragmentAdapter adapter = new BannerFragmentAdapter(
//										fa.getSupportFragmentManager(),
//										contents);
//								headerHolder.bannerViewPager
//										.setAdapter(adapter);
//								headerHolder.bannerViewPager.setCurrentItem(0);// 设置当前显示标签页为第一页
//								headerHolder.bannerViewPager
//										.setOffscreenPageLimit(2);
//								LayoutParams lp = headerHolder.cursor
//										.getLayoutParams();
//
//								lp.width = headerHolder.cursorBackground.getWidth()
//										/ array.length();
//
//								headerHolder.cursor.setLayoutParams(lp);
//								headerHolder.bannerViewPager
//										.setOnPageChangeListener(new BannerOnPageChangedListener(
//												headerHolder.bannerViewPager,
//												headerHolder.cursorBackground
//														.getWidth()
//														/ array.length(),
//												headerHolder.cursor));
//								if (array.length() <= 1) {
//									headerHolder.cursor
//											.setVisibility(View.INVISIBLE);
//									headerHolder.cursorBackground
//											.setVisibility(View.INVISIBLE);
//								}
//
//							}
//						}
//
//					});
		} else if (holder instanceof RecyclerViewHolder) {
			RecyclerViewHolder genericViewHolder = (RecyclerViewHolder) holder;
			try {
				JSONObject product = array.get(position
						- HEADER_PAGER_LAYOUT);
				if (product != null) {
					// getString(R.string.hint_reg_waityzm,arg0/1000)
					genericViewHolder.iv_hairstyle.setImageBitmap(defualtBm);
					aq.id(genericViewHolder.iv_hairstyle).image(
							CommonUtils.getJsonString(product, "hairPhotoUrl"),
							true, true, 200, 0,null , Constants.FADE_IN);
//					aq.id(genericViewHolder.iv_headimg).image(
//							CommonUtils.getJsonString(product, "iconPhotoUrl"),
//							true, true, 200, 0, null, Constants.FADE_IN);

//					genericViewHolder.tv_name.setText(CommonUtils
//							.getJsonString(product, "name"));
//					genericViewHolder.tv_post.setText(CommonUtils
//							.getJsonString(product, "levlNames"));
					Log.d("sort","MainAdapter:onBindViewHolder: "+product);
					genericViewHolder.tv_intro.setText(CommonUtils
							.getJsonString(product, "infoDescription"));
//					genericViewHolder.tv_collections.setText(mContext
//							.getString(R.string.txt_collection, CommonUtils
//									.getJsonInt(product, "collectCount")));
//					genericViewHolder.tv_orders.setText(mContext.getString(
//							R.string.txt_order,
//							CommonUtils.getJsonInt(product, "buyCount")));
//					genericViewHolder.tv_type.setText("洗剪吹");
////					genericViewHolder.tv_price.setText(mContext.getString(
//							R.string.txt_price,
//							CommonUtils.getJsonInt(product, "infoValues")));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	@Override
	public int getItemViewType(int position) {
		if (isPositionHeader(position)) {
			return TYPER_PAGER;
		}
		return TYPE_ITEM;
	}

	public boolean isPositionHeader(int position) {
		return position == 0;
	}

	@Override
	public int getItemCount() {
		return array.size() + HEADER_PAGER_LAYOUT;
	}

	public class HeaderViewHolder extends RecyclerView.ViewHolder {
		ViewPager bannerViewPager;
		ImageView cursor;
		ImageView cursorBackground;
		PagerContainer pc;
		ViewPager sylistViewPager;

		public HeaderViewHolder(View itemView) {
			super(itemView);
			this.bannerViewPager = (ViewPager) itemView
					.findViewById(R.id.vp_banner);
			this.sylistViewPager = (ViewPager) itemView.findViewById(R.id.ddd);
			this.pc = (PagerContainer) itemView
					.findViewById(R.id.vp_hairdresser);
			this.cursor = (ImageView) itemView.findViewById(R.id.iv_cursor);
			this.cursorBackground = (ImageView) itemView
					.findViewById(R.id.iv_cursor_bg);

		}

	}

	public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
			View.OnClickListener {

		ImageView iv_hairstyle;
		ImageView iv_headimg;
		TextView tv_name;
		TextView tv_post;
		TextView tv_words;
		TextView tv_collections;
		TextView tv_orders;
		TextView tv_type;
		TextView tv_intro;
		Button btn_appointment;
		ImageView iv_collection;

		public RecyclerViewHolder(View view) {
			super(view);
			// implementing onClickListener
			iv_hairstyle = (ImageView) view.findViewById(R.id.iv_hairstyle);
			iv_headimg = (ImageView) view.findViewById(R.id.iv_headimg);
			btn_appointment = (Button) view.findViewById(R.id.btn_appointment);
			tv_name = (TextView) view.findViewById(R.id.tv_name);
			tv_post = (TextView) view.findViewById(R.id.tv_post);
			tv_words = (TextView) view.findViewById(R.id.tv_words);
			tv_collections = (TextView) view.findViewById(R.id.tv_collections);
			tv_orders = (TextView) view.findViewById(R.id.tv_orders);
			tv_type = (TextView) view.findViewById(R.id.tv_type);
			tv_intro = (TextView) view.findViewById(R.id.tv_intro);
			iv_collection = (ImageView) view.findViewById(R.id.iv_collection);
			btn_appointment.setOnClickListener(new AppointmentOnClickListener());
			iv_hairstyle.setOnClickListener(new HairstyleOnClickListener());
//			iv_collection.setOnClickListener(new CollectionOnClickListener());
			// iv_hairstyle.setOnClickListener(this);
		}

		@Override
		public void onClick(View view) {

			mOnGridItemSelectedListener.onGridItemClick(view, getPosition()
					- HEADER_PAGER_LAYOUT);
		}

		public class AppointmentOnClickListener implements
				View.OnClickListener {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mOnGridItemSelectedListener.onItemAppointment(v, getPosition());
			}
		}

		public class HairstyleOnClickListener implements
				View.OnClickListener {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mOnGridItemSelectedListener.onHairStyleClick(v, getPosition());
			}
		}
		public class DresserOnClickListener implements
				View.OnClickListener {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mOnGridItemSelectedListener.onHairDresserClick(v, getPosition());
			}
		}
		public class CollectionOnClickListener implements
				View.OnClickListener {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated v stub
				mOnGridItemSelectedListener.onItemCollection(v, getPosition());
			}
		}
	}

	public class BannerOnPageChangedListener implements OnPageChangeListener {
		private ViewPager view;
		private int offset;
		private int currIndex;
		private ImageView cursor;

		public BannerOnPageChangedListener(ViewPager view, int offset,
				ImageView cursor) {
			this.view = view;
			this.offset = offset;
			this.cursor = cursor;
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			BannerFragmentAdapter bf = (BannerFragmentAdapter) view
					.getAdapter();
			BannerFragment b = bf.getItem(arg0);
			ObjectAnimator oa= ObjectAnimator.ofFloat(cursor,"translationX" , currIndex * offset, arg0 * offset);
			oa.setDuration(200);
			oa.start();
//			Animation animation = new TranslateAnimation(currIndex * offset,
//					arg0 * offset, 0, 0);// 平移动画
//			currIndex = arg0;
//			animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
//			animation.setDuration(200);// 动画持续时间0.2秒
//			cursor.startAnimation(animation);// 是用ImageView来显示动画的
			currIndex=arg0;
		}

	}

	public class SyListOnPageChangedListener implements OnPageChangeListener {
		ViewPager root;

		public SyListOnPageChangedListener(ViewPager root) {
			this.root = root;

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
			if (root != null) {
				root.invalidate();
			}
		}

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			if (arg0 == 0) {
				root.setX(mContext.getResources().getDimension(
						R.dimen.viewpager_first_margin_left));
			}
			if (arg0 < array.size() - 1 && arg0 > 0) {
				root.setX(centerX);
			}
			if (arg0 == array.size() - 1) {
				root.setX(mContext.getResources().getDimension(
						R.dimen.viewpager_first_margin_right));
			}
		}

	}

}
